package com.fyzk.activity.chongzhi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.fyzk.activity.app.AppToast;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.TopTitleView;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tyjc.lottery.R;

public class Recharge_AlipayWapActivity extends Activity implements onTopTitleClickListener {

    protected TopTitleView zfb_title_rl;

    protected String amount;
    private int minMoney = 1;
    com.tencent.smtt.sdk.WebView webView;

    private final int ALIPAY = 2;
    private final int SUCCESS = 3;
    private final int CANCLE = 4;

    String rechargeUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_recharge_alipaywap);
        rechargeUrl = getIntent().getStringExtra("wap_redicturl");
        info();
    }

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            LogUtil.e("handleMessage>>");
            parserMessage(msg);
        }
    };


    private void info() {
        zfb_title_rl = findViewById(R.id.topview);
        zfb_title_rl.setOnTitleClickListener(this);
        hideSoftInput();
        webView = findViewById(R.id.web_view_alipay);
        WebSettings settings = webView.getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        settings.setDomStorageEnabled(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
        settings.setAllowFileAccess(false);
        settings.setTextSize(WebSettings.TextSize.NORMAL);
        webView.setVerticalScrollbarOverlay(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setVisibility(View.VISIBLE);
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webView.loadUrl(getIntent().getStringExtra("wap_redicturl"));
    }


    protected void parserMessage(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
            case ALIPAY:
                String returnUrl = msg.obj.toString();
                LogUtil.d("returnUrl>>>" + returnUrl);
                webView.loadUrl(returnUrl);
                break;
            case SUCCESS:
                AppToast.getToast().show("支付成功");
                Recharge_AlipayWapActivity.this.setResult(IntentParamUtils.PAY_OK);
                Recharge_AlipayWapActivity.this.finish();
                break;
            case CANCLE:
                AppToast.getToast().show("支付取消");
                Recharge_AlipayWapActivity.this.finish();
                break;
        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onRight2Click() {

    }


    private class MyWebViewClient extends WebViewClient {


        // 在WebView中而不是默认浏览器中显示页面
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            final PayTask task = new PayTask(Recharge_AlipayWapActivity.this);
            //处理订单信息
            boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
                @Override
                public void onPayResult(final H5PayResultModel result) {
                    // 支付结果返回
                    final String url = result.getReturnUrl();
                    //处理返回结果
                    if (!TextUtils.isEmpty(url)) {

                        Message msg = mHandler.obtainMessage();
                        msg.obj = url;
                        msg.what = ALIPAY;
                        mHandler.sendMessage(msg);
                    } else {
                        mHandler.sendEmptyMessage(CANCLE);
                    }
                }
            });

            /**
             * 判断是否成功拦截
             * 若成功拦截，则无需继续加载该URL；否则继续加载
             */
            if (!isIntercepted) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                } else if (url.startsWith("https://cashier.ehking.com/receipt/paymentSuccess") || url.startsWith
                        ("http://101.200.196.69/lotserver/index.jsp")) {
                    mHandler.sendEmptyMessage(SUCCESS);
                } else {
                    view.loadUrl(url);
                }
            }
//            final String ex = task.fetchOrderInfoFromH5PayUrl(url);
//            if (!TextUtils.isEmpty(ex)) {
//                //调用支付接口进行支付
//                new Thread(new Runnable() {
//                    public void run() {
//                        z.a result = task.h5Pay(ex, true);
//                        //处理返回结果
//                        if (!TextUtils.isEmpty(result.a())) {
//
//                            Message msg = mHandler.obtainMessage();
//                            msg.obj = result.a().toString();
//                            msg.what = ALIPAY;
//                            mHandler.sendMessage(msg);
//                        } else {
//                            mHandler.sendEmptyMessage(CANCLE);
//                        }
//                    }
//                }).start();
//            } else {
//                if (url.startsWith("tel:")) {
//                    Intent intent = new Intent(Intent.ACTION_VIEW,
//                            Uri.parse(url));
//                    startActivity(intent);
//                } else if (url.startsWith("https://cashier.ehking.com/receipt/paymentSuccess") || url.startsWith
//                        ("http://101.200.196.69/lotserver/index.jsp")) {
//                    mHandler.sendEmptyMessage(SUCCESS);
//                } else {
//                    view.loadUrl(url);
//                }
//            }

            return true;
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(Recharge_AlipayWapActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
        }


        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view,
                                                          String url) {
            // TODO Auto-generated method stub
            WebResourceResponse response = super.shouldInterceptRequest(view, url);
            return response;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
            LogUtil.v("url>>>" + url);
        }

    }


    public void hideSoftInput() throws NullPointerException {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context
                .INPUT_METHOD_SERVICE);
        View foucusView = this.getCurrentFocus();
        if (null == foucusView) {
            return;
        }
        // Log.v(TAG, foucusView.getId()+"");
        if (inputMethodManager.isActive() && null != foucusView) {
            inputMethodManager.hideSoftInputFromWindow(
                    foucusView.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.removeAllViews();
            try {
                webView.destroy();
            } catch (Throwable t) {
            }
            webView = null;
        }
    }
}
